package com.eventm.daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.eventm.dao.IUserDao;
import com.eventm.model.User;

@Repository("userDao")
public class UserDaoImpl implements IUserDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional
	public void saveUser(User user) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (Exception e) {
			if (tx!=null) tx.rollback();
		    throw e;
		}finally{
			session.close();
		}
	}

	@Transactional
	public void delete(Integer userId) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			User user = (User) session.get(User.class, userId);
			session.delete(user);
			tx.commit();
		} catch (Exception e) {
			if (tx!=null) tx.rollback();
		    throw e;
		}finally{
			session.close();
		}
	}

	@Transactional(readOnly = true)
	public User findById(Integer userId)throws Exception {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			User user = (User) session.get(User.class, userId);
			tx.commit();
			return user;
		} catch (Exception e) {
			if(tx!=null) tx.rollback();
			throw e;
		}finally{
			session.close();
		}
	}

	@Transactional(readOnly = true)
	public List<User> findAll() {
		return null;
	}

}
